package com.hyf.ucenter.controller;

import com.google.gson.Gson;
import com.hyf.commonutils.JwtUtils;
import com.hyf.service.config.exception.GuliException;
import com.hyf.ucenter.entity.Member;
import com.hyf.ucenter.service.MemberService;
import com.hyf.ucenter.util.ConstantPropertiesUtil;
import com.hyf.ucenter.util.HttpClientUtils;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

// 微信登录实现累
//@CrossOrigin
@Controller//注意这里没有配置 @RestController 因为不需要返回结果所以用Controller就可以了
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
	
	@Autowired// 微信登陆
	private MemberService memberService;
	
	
	// 获取扫描人的信息
	@GetMapping("callback")
	public String callback(String code, String state) {
		
		try{
			
			// 获取code值，临时票据，累是有验证码
			//			System.out.println("code:"+code);
//			System.out.println("state:"+state);
			
			//向认证服务器发送请求换取access_token
			//2、拿着code请求 微信的固定地址，得到两个值access_token和openid
			String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
					"?appid=%s" +
					"&secret=%s" +
					"&code=%s" +
					"&grant_type=authorization_code";
			
			String accessTokenUrl = String.format(baseAccessTokenUrl,
					ConstantPropertiesUtil.WX_OPEN_APP_ID,
					ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
					code);
			//请求这个拼接好的地址，得到返回两个值access_token和openid
			//使用httpclient发送请求，得到返回结果
			String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
			// 打印查看一下结果
			System.out.println("accessTokenInfo:"+accessTokenInfo);
			//使用gson转换工具Gson
			Gson gson = new Gson();
			HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
			
			String access_token = (String)mapAccessToken.get("access_token");
			String openid = (String)mapAccessToken.get("openid");
			
			
			//判断该微信信息是否注册过
			Member menber = memberService.getByOpenid(openid);
			if (menber == null){
				//3\拿着access_token和openid，再去请求微信提供的固定地址，获取扫描人信息
				//访问微信的资源服务器，获取用户信息
				String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
						"?access_token=%s" +
						"&openid=%s";
				
				//再次拼接微信地址
				String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
				
				String userInfo = HttpClientUtils.get(userInfoUrl);
				
				System.out.println("用户信息:"+userInfo);
				
				//获取的微信个人信息json信息进行转换
				HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
				String nickname = (String)userInfoMap.get("nickname");//昵称
				String headimgurl = (String)userInfoMap.get("headimgurl");//头像
				
				//把微信信息注册到数据库中
				menber = new Member();
				menber.setNickname(nickname);
				menber.setOpenid(openid);
				menber.setAvatar(headimgurl);
				memberService.save(menber);
			}
			
			//使用jwt生成token字符串
			String jwtToken = JwtUtils.getJwtToken(menber.getId(), menber.getNickname());
			//返回首页面
			return "redirect:http://localhost:3000?token="+jwtToken;
		} catch (Exception e) {
			e.printStackTrace();
			throw new GuliException(20001,"登录失败");
		}
	}
	
	// 生成扫描的二维码
	@GetMapping("/login")
	public String getWxCode(){
		
		//固定地址，后面拼接参数
		// 微信开放平台授权baseUrl
		String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
		"?appid=%s" +
		"&redirect_uri=%s" +
		"&response_type=code" +
		"&scope=snsapi_login" +
		"&state=%s" +
		"#wechat_redirect";
		
		// 对redirect_uri进行编码进行URLEncode编码
		String redirectUri = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
		try {
			redirectUri = URLEncoder.encode(redirectUri, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		
		String url = String.format(
				baseUrl,
				ConstantPropertiesUtil.WX_OPEN_APP_ID,
				ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL,
				"atguigu"
		);
		
		// 从定向请求微信地址
		return "redirect:" + url;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/*
	// 生成扫描的二维码
	@GetMapping("login")
	public String genQrConnect(HttpSession session) {
		// 微信开放平台授权baseUrl
		String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
		"?appid=%s" +
		"&redirect_uri=%s" +
		"&response_type=code" +
		"&scope=snsapi_login" +
		"&state=%s" +
		"#wechat_redirect";
		//对redirectUrl进行URLEncoder编码
		// 回调地址
		String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
		try {
			redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
		} catch (UnsupportedEncodingException e) {
			throw new GuliException(20001, e.getMessage());
		}
		// 防止csrf攻击（跨站请求伪造攻击）
		//String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
		String state = "imhelen";//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名
		System.out.println("state = " + state);
		// 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
		//键："wechar-open-state-" + httpServletRequest.getSession().getId()
		//值：satte
		//过期时间：30分钟

		//生成qrcodeUrl
		String qrcodeUrl = String.format(
				baseUrl,
				ConstantPropertiesUtil.WX_OPEN_APP_ID,
				redirectUrl,
				state);
		
		return "redirect:" + qrcodeUrl;
	}
	
	
	
	//获取扫描人信息，添加数据
	@GetMapping("callback")
	public String callback(String code, String state, HttpSession session) {
		//获取code值临时票据，类似于验证码
		//得到授权临时票据code
		System.out.println(code);
		System.out.println(state);
		//从redis中将state获取出来，和当前传入的state作比较
		//如果一致则放行，如果不一致则抛出异常：非法访问
		//向认证服务器发送请求换取access_token
		String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
		"?appid=%s" +
		"&secret=%s" +
		"&code=%s" +
		"&grant_type=authorization_code";
		String accessTokenUrl = String.format(baseAccessTokenUrl,
				ConstantPropertiesUtil.WX_OPEN_APP_ID,
				ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
				code);
		String result = null;
		try {
			result = HttpClientUtils.get(accessTokenUrl);
			System.out.println("accessToken=============" + result);
		} catch (Exception e) {
			throw new GuliException(20001, "获取access_token失败");
		}
		
		//解析json字符串
		Gson gson = new Gson();
		HashMap map = gson.fromJson(result, HashMap.class);
		String accessToken = (String)map.get("access_token");
		String openid = (String)map.get("openid");
		//查询数据库当前用用户是否曾经使用过微信登录
		Member member = memberService.getByOpenid(openid);
		if(member == null){// 判断member 是否为空，为空的话做一个添加
			System.out.println("新用户注册");
			//访问微信的资源服务器，获取用户信息
			String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
			"?access_token=%s" +
			"&openid=%s";
			String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
			String resultUserInfo = null;
			try {
				resultUserInfo = HttpClientUtils.get(userInfoUrl);
				System.out.println("resultUserInfo==========" + resultUserInfo);
				
				//解析json
				HashMap<String, Object> mapUserInfo = gson.fromJson(resultUserInfo, HashMap.class);
				String nickname = (String)mapUserInfo.get("nickname");// 昵称
				
				String headimgurl = (String)mapUserInfo.get("headimgurl");// 头像
				
				//向数据库中插入一条记录
				member = new Member();
				member.setNickname(nickname);
				member.setOpenid(openid);
				member.setAvatar(headimgurl);
				memberService.save(member);
			} catch (Exception e) {
				throw new GuliException(20001, "获取用户信息失败");
			}
			
		}
		

		// 生成jwt
		String token = JwtUtils.getJwtToken(member.getId(),member.getNickname());
		//存入cookie
     //CookieUtils.setCookie(request, response, "guli_jwt_token", token);
     //因为端口号不同存在蛞蝓问题，cookie不能跨域，所以这里使用url重写
		return "redirect:http://localhost:3000?token=" + token;
		
	
	}*/
	
}
